package cn.life.business.excel.controller;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.life.business.inspect.entity.po.Inspect;
import cn.life.business.inspect.entity.vo.InspectVo;
import cn.life.business.inspect.service.InspectService;
import cn.life.common.utils.CExportExcelView;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.ModelMap;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.View;

/**
 * @author 王振宇
 * @Description:
 * @Date 2018-09-11 09:27:25
 */
@RestController
@RequestMapping("excel")
public class ExcelController {

    @Autowired
    private InspectService inspectService;


    @PostMapping("/export")
    public ModelAndView exportInfo(HttpServletRequest request, HttpServletResponse response, String projectId) {
        try
        {
            HSSFWorkbook workbook = new HSSFWorkbook();
            HSSFSheet sheet = workbook.createSheet("Sheet1");
            HSSFCellStyle style0 = workbook.createCellStyle();//设置单元格样式
            //style0.setAlignment(HSSFCellStyle.ALIGN_CENTER);
            style0.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
            style0.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 左右居中
            style0.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 上下居中
            style0.setBorderBottom(HSSFCellStyle.BORDER_THIN); //下边框
            style0.setBorderLeft(HSSFCellStyle.BORDER_THIN);//左边框
            style0.setBorderTop(HSSFCellStyle.BORDER_THIN);//上边框
            style0.setBorderRight(HSSFCellStyle.BORDER_THIN);//右边框
            style0.setFillForegroundColor(IndexedColors.YELLOW.getIndex());
            style0.setFillPattern(CellStyle.SOLID_FOREGROUND);
            style0.setLocked(true);   //锁定单元格
            style0.setWrapText(true);// 自动换行
            HSSFFont font=workbook.createFont();//设置字体
            font.setColor(HSSFColor.BLACK.index);//HSSFColor.VIOLET.index //字体颜色
            font.setFontHeightInPoints((short)12);
            font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);         //字体增粗
            //把字体应用到当前的样式
            style0.setFont(font);

            HSSFCellStyle style = workbook.createCellStyle();
            //style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
            style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
            style.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 左右居中
            style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 上下居中
            style.setBorderBottom(HSSFCellStyle.BORDER_THIN); //下边框
            style.setBorderLeft(HSSFCellStyle.BORDER_THIN);//左边框
            style.setBorderTop(HSSFCellStyle.BORDER_THIN);//上边框
            style.setBorderRight(HSSFCellStyle.BORDER_THIN);//右边框

            style.setLocked(true);
            style.setWrapText(true);// 自动换行
            HSSFRow row1 = sheet.createRow(0); //创建第一行
            sheet.setDefaultColumnWidth(30);
            HSSFCell cell = row1.createCell(0);   //创建第一行的单元格
            cell.setCellValue(new HSSFRichTextString("人员信息"));
            cell.setCellStyle(style0);
            cell = row1.createCell(1);
            cell.setCellValue(new HSSFRichTextString("合格率"));
            cell.setCellStyle(style0);
            cell = row1.createCell(2);

            //获取导出数据
            HSSFCell [] cells = new HSSFCell[2];
            InspectVo inspectVo = new InspectVo();
            inspectVo.setProjectId(Long.valueOf(projectId));
            List<InspectVo> list = inspectService.statisticsExcel(inspectVo);
            int rowNum = 1;
            for(int j = 0;j<list.size();j++)
            {
                InspectVo record = list.get(j);
                HSSFRow row = sheet.createRow(rowNum);
                System.out.println(Float.parseFloat(String.format("%.2f",record.getQualificatioRate()))*100+"%");
                row.createCell(0).setCellValue(record.getPersonLiableName());
                row.createCell(1).setCellValue(Float.parseFloat(String.format("%.2f",record.getQualificatioRate()))*100+"%");
                rowNum++;
            }


            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            try {
                workbook.write(baos);//将数据写入工作簿
                byte[] ba = baos.toByteArray();
                ByteArrayInputStream bais = new ByteArrayInputStream(ba);
                ByteArrayInputStream inputstream = bais;
                Date date = new Date();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
                String name = sdf.format(date);
                String downloadFileName=name+"合格率统计.xls";
                response.setHeader("Content-Disposition", "attachment; filename="+new String(downloadFileName.getBytes("gb2312"),"iso-8859-1"));
                response.setContentType("application/x-download");// 设置为下载application/x-download
                response.addHeader("content-type ", "application/x-msdownload");
                response.setContentType("application/octet-stream");

                BufferedInputStream bis = new BufferedInputStream(inputstream);
                FileCopyUtils.copy(bis, response.getOutputStream());
                response.getOutputStream().flush();
                response.getOutputStream().close();
                response.getOutputStream().close();


                ModelMap model = new ModelMap();
                model.addAttribute("workBook", workbook);
                model.addAttribute("fileName", "考勤信息表");
                return new ModelAndView(new CExportExcelView(),model);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }catch(Exception e){
            e.printStackTrace();
        }

        return null;

    }
}
